package com.huawei.translate.api;

import com.huawei.translate.model.Renter;
import com.huawei.translate.persistence.RenterRepository;
import com.huawei.translate.vo.user.RenterDto;
import com.huawei.translate.vo.user.UpdateCategoryRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/api/user")
@Api(value = "translate Service API", description = "User auth")
public class UserApi {

    @Autowired
    private RenterRepository renterRepository;

    @ApiOperation(value = "login", httpMethod = "POST")
    @RequestMapping(method = GET, value = "/login")
    public ResponseEntity<RenterDto> login(@RequestParam(value = "username", required = true) String username,
                                           @RequestParam(value = "password", required = true) String password) {

        Renter renter = renterRepository.findByAppKey(username).size() <= 0 ? null : renterRepository.findByAppKey(username).get(0);

        if (renter == null || !renter.getAppSecret().equals(password)) {
            return new ResponseEntity(HttpStatus.FORBIDDEN);
        }

        RenterDto renterDto = toDto(renter);

        return new ResponseEntity(renterDto, HttpStatus.OK);
    }

    private RenterDto toDto(Renter renter) {
        return RenterDto.toDto(renter);
    }

    @ApiOperation(value = "update", httpMethod = "POST")
    @RequestMapping(method = POST, value = "/category")
    public ResponseEntity update(@RequestBody UpdateCategoryRequest request) {

        Renter renter = renterRepository.findById(request.getId());
        if (renter == null) {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
        renter.setCategory(request.getCategory());
        renterRepository.save(renter);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "check", httpMethod = "GET")
    @RequestMapping(value = "/{appKey}", method = GET)
    public ResponseEntity<String> check(@PathVariable String appKey) {
        List<Renter> renters = renterRepository.findByAppKey(appKey);
        if (renters.size() > 0) {
            return new ResponseEntity(HttpStatus.FOUND);
        }
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
}
